package com.fdl.service.security.impl;

import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;

import com.fdl.common.exception.security.LoginTimeOutException;
import com.fdl.dao.model.security.Permission;
import com.fdl.dao.model.security.User;

/**
 * 
 * @description 
 * @project: hb-intra
 * @Date:2010-8-4
 * @version  1.0
 * @Company: 33e9
 * @author zhangYong.huang
 */
public class SecurityUtils {
	/**
	 * 系统管理员
	 */
	public static final String PERMISSION_NAME_SUPER_USER = "AUTH_ROOT";

	public static Authentication getCurrentAuthentication() {
		return SecurityContextHolder.getContext().getAuthentication();
	}

	/**
	 * 获取当前用户
	 * @return
	 */
	public static User getCurrentUser() throws LoginTimeOutException  {
		Authentication authentication = getCurrentAuthentication();

		if (authentication == null
				|| authentication instanceof AnonymousAuthenticationToken) {
			throw new LoginTimeOutException();
		} else {
			return (User) authentication.getPrincipal();
		}
	}

	public static void setCurrentUser(User user) {
		Authentication authentication = getCurrentAuthentication();

		UsernamePasswordAuthenticationToken newAuth = new UsernamePasswordAuthenticationToken(
				user, authentication.getCredentials(), user.getAuthorities());
		newAuth.setDetails(authentication.getDetails());

		SecurityContextHolder.getContext().setAuthentication(newAuth);
	}

	/**
	 * 当前用户是否有此权限
	 * @param auth
	 * @return
	 */
	public static boolean hasPermission(String auth) {
		Authentication authentication = getCurrentAuthentication();
		if (authentication != null) {
			GrantedAuthority[] authorities = authentication.getAuthorities();

			for (int i = 0; i < authorities.length; i++) {
				if (auth.equals(authorities[i].getAuthority())) {
					return true;
				}
			}
		}

		return false;
	}

	/**
	 * 是否是系统管理员
	 * @return
	 */
	public static boolean isSuperUser() {
		return hasPermission(Permission.PERMISSION_NAME_SUPER_USER);
	}
}
